package com.draven.mall.controller;

import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.Rider;
import com.draven.mall.entity.Order;
import com.draven.mall.service.OrderService;
import com.draven.mall.service.RiderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 骑手订单控制器
 */
@RestController
@RequestMapping("/api/rider/order")
public class RiderOrderController {

    private static final Logger log = LoggerFactory.getLogger(RiderOrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private RiderService riderService;

    /**
     * 获取待接单订单列表
     */
    @GetMapping("/available")
    public ApiResponse getAvailableOrders(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        Map<String, Object> result = orderService.getAvailableOrders(page, size);
        return ApiResponse.success(result);
    }

    /**
     * 骑手接单
     */
    @PostMapping("/take")
    public ApiResponse takeOrder(
            @RequestParam Long orderId,
            @RequestParam Long riderId) {
        boolean success = orderService.takeOrder(orderId, riderId);
        if (success) {
            return ApiResponse.success("接单成功");
        } else {
            return ApiResponse.error("接单失败，订单已被接走或状态异常");
        }
    }

    /**
     * 完成订单配送
     */
    @PostMapping("/complete")
    public ApiResponse completeOrder(
            @RequestParam Long orderId,
            @RequestParam Long riderId) {
        boolean success = orderService.completeOrder(orderId, riderId);
        if (success) {
            return ApiResponse.success("订单已完成");
        } else {
            return ApiResponse.error("操作失败，订单状态异常");
        }
    }

    /**
     * 获取骑手配送中的订单
     */
    @GetMapping("/in-progress")
    public ApiResponse getInProgressOrders(
            @RequestParam Long riderId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        Map<String, Object> result = orderService.getInProgressOrders(riderId, page, size);
        return ApiResponse.success(result);
    }

    /**
     * 获取骑手已完成的订单
     */
    @GetMapping("/completed")
    public ApiResponse getCompletedOrders(
            @RequestParam Long riderId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {
        Map<String, Object> result = orderService.getCompletedOrders(riderId, page, size);
        return ApiResponse.success(result);
    }

    /**
     * 切换骑手抢单状态
     */
    @PostMapping("/toggle-grab")
    public ApiResponse toggleGrabOrderStatus(
            @RequestParam Long riderId,
            @RequestParam Integer status) {
        boolean success = riderService.updateGrabOrderStatus(riderId, status);
        if (success) {
            String statusText = status == 1 ? "开启" : "关闭";
            return ApiResponse.success(statusText + "抢单成功");
        } else {
            return ApiResponse.error("操作失败");
        }
    }

    /**
     * 获取骑手抢单状态
     */
    @GetMapping("/grab-status")
    public ApiResponse getGrabOrderStatus(@RequestParam Long riderId) {
        Rider rider = riderService.getById(riderId);
        if (rider != null) {
            return ApiResponse.success(rider.getGrabOrderStatus());
        } else {
            return ApiResponse.error("骑手不存在");
        }
    }

    /**
     * 获取订单地址坐标信息（用于导航）
     */
    @GetMapping("/location")
    public ApiResponse getOrderLocation(@RequestParam("orderId") Long orderId) {
        try {
            // 获取订单信息
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }
            
            // 创建坐标信息响应对象
            Map<String, Object> locationInfo = new HashMap<>();
            locationInfo.put("address", order.getAddress());
            
            // 检查订单地址
            String address = order.getAddress();
            if (address == null || address.trim().isEmpty()) {
                return ApiResponse.error("订单地址为空");
            }
            
            log.info("获取订单坐标, 订单ID: {}, 地址: {}", orderId, address);
            
            // 处理不同城市的地址
            double latitude = 0;
            double longitude = 0;
            
            // 简单地址解析示例（实际应用中应当接入高德/百度等地图API）
            if (address.contains("北京")) {
                // 北京市默认坐标
                latitude = 39.908823;
                longitude = 116.397470;
            } else if (address.contains("上海")) {
                // 上海市默认坐标
                latitude = 31.230416;
                longitude = 121.473701;
            } else if (address.contains("广州")) {
                // 广州市默认坐标
                latitude = 23.129163;
                longitude = 113.264435;
            } else if (address.contains("深圳")) {
                // 深圳市默认坐标
                latitude = 22.543096;
                longitude = 114.057865;
            } else if (address.contains("杭州")) {
                // 杭州市默认坐标
                latitude = 30.274085;
                longitude = 120.155070;
            } else {
                // 如果不能识别城市，使用北京默认坐标
                latitude = 39.908823;
                longitude = 116.397470;
            }
            
            // 解析详细地址微调坐标（简单模拟，实际需要调用地图API）
            // 这里简单根据门牌号数字调整坐标，实际项目应接入地图API
            if (address.matches(".*?([0-9]+)号.*?")) {
                String numberStr = address.replaceAll(".*?([0-9]+)号.*?", "$1");
                try {
                    int number = Integer.parseInt(numberStr);
                    // 微调经纬度
                    double offset = (number % 100) * 0.0001;
                    latitude += offset;
                    longitude += offset;
                } catch (NumberFormatException e) {
                    // 解析失败，忽略
                    log.warn("解析门牌号失败: {}", numberStr);
                }
            }
            
            locationInfo.put("latitude", latitude);
            locationInfo.put("longitude", longitude);
            
            log.info("返回地址坐标信息: 经度={}, 纬度={}", longitude, latitude);
            return ApiResponse.success(locationInfo);
        } catch (Exception e) {
            log.error("获取订单地址坐标异常", e);
            return ApiResponse.error("获取坐标信息异常");
        }
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/detail")
    public ApiResponse getOrderDetail(@RequestParam("orderId") Long orderId) {
        try {
            log.info("获取订单详情, orderId: {}", orderId);
            if (orderId == null) {
                return ApiResponse.error("订单ID不能为空");
            }
            
            // 获取基本订单信息
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }
            
            // 获取订单商品信息
            Map<String, Object> orderDetail = orderService.getOrderDetailWithItems(orderId);
            
            // 确保商品数据可以被解析
            if (orderDetail.containsKey("items") && orderDetail.get("items") != null) {
                log.info("成功获取订单商品信息");
            } else {
                log.warn("订单 {} 没有商品信息", orderId);
            }
            
            return ApiResponse.success(orderDetail);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ApiResponse.error("获取订单详情失败: " + e.getMessage());
        }
    }
}

/**
 * 骑手统计相关接口
 */
@RestController
@RequestMapping("/api/rider/stats")
class RiderStatsController {
    
    private static final Logger log = LoggerFactory.getLogger(RiderStatsController.class);
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private RiderService riderService;
    
    /**
     * 获取骑手仪表盘统计数据
     */
    @GetMapping("/dashboard")
    public ApiResponse getDashboardStats(@RequestParam Long riderId) {
        try {
            log.info("获取骑手仪表盘统计数据, riderId: {}", riderId);
            
            // 获取日期信息
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date());
            
            // 获取今日完成订单
            Map<String, Object> completedOrders = orderService.getCompletedOrders(riderId, 1, 100);
            List<Order> orders = (List<Order>) completedOrders.get("records");
            
            // 计算今日订单数和收入
            int todayOrders = 0;
            BigDecimal todayIncome = BigDecimal.ZERO;
            
            if (orders != null && !orders.isEmpty()) {
                for (Order order : orders) {
                    if (order.getUpdatedTime() != null) {
                        String orderDate = sdf.format(order.getUpdatedTime());
                        if (today.equals(orderDate)) {
                            todayOrders++;
                            if (order.getDeliveryFee() != null) {
                                todayIncome = todayIncome.add(order.getDeliveryFee());
                            }
                        }
                    }
                }
            }
            
            // 构建返回数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("todayOrders", todayOrders);
            stats.put("todayIncome", todayIncome);
            // 注意：不返回inProgressOrders，由前端通过loadInProgressOrders API获取
            
            return ApiResponse.success(stats);
        } catch (Exception e) {
            log.error("获取骑手仪表盘统计数据异常", e);
            return ApiResponse.error("获取骑手统计数据异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取骑手每日配送统计
     */
    @GetMapping("/daily")
    public ApiResponse getDailyStats(
            @RequestParam Long riderId,
            @RequestParam(required = false) String date) {
        try {
            // 如果未提供日期，则使用今天
            if (date == null || date.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                date = sdf.format(new Date());
            }
            
            log.info("获取骑手每日统计, riderId: {}, date: {}", riderId, date);
            
            // 获取骑手的已完成订单
            Map<String, Object> result = orderService.getCompletedOrders(riderId, 1, 100);
            List<Order> orders = (List<Order>) result.get("records");
            
            // 计算当天的订单数和收入
            int orderCount = 0;
            BigDecimal totalEarnings = BigDecimal.ZERO;
            
            if (orders != null && !orders.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                
                for (Order order : orders) {
                    // 只统计指定日期的订单
                    if (order.getUpdatedTime() != null) {
                        String orderDate = sdf.format(order.getUpdatedTime());
                        if (date.equals(orderDate)) {
                            orderCount++;
                            if (order.getDeliveryFee() != null) {
                                totalEarnings = totalEarnings.add(order.getDeliveryFee());
                            }
                        }
                    }
                }
            }
            
            // 构建响应数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("orderCount", orderCount);
            stats.put("earnings", totalEarnings.toString());
            stats.put("date", date);
            
            return ApiResponse.success(stats);
        } catch (Exception e) {
            log.error("获取骑手每日统计异常", e);
            return ApiResponse.error("获取统计数据异常");
        }
    }
    
    /**
     * 获取骑手总配送统计
     */
    @GetMapping("/total")
    public ApiResponse getTotalStats(@RequestParam Long riderId) {
        try {
            log.info("获取骑手总配送统计, riderId: {}", riderId);
            
            // 获取骑手的所有已完成订单
            Map<String, Object> result = orderService.getCompletedOrders(riderId, 1, 1000); // 假设最多1000单
            
            // 构建响应数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalOrders", result.get("total"));
            
            return ApiResponse.success(stats);
        } catch (Exception e) {
            log.error("获取骑手总配送统计异常", e);
            return ApiResponse.error("获取统计数据异常");
        }
    }
} 